package com.zareal.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zareal.ymcc.constans.CommonConstants;
import com.zareal.ymcc.domain.BlackList;
import com.zareal.ymcc.mapper.BlackListMapper;
import com.zareal.ymcc.result.JSONResult;
import com.zareal.ymcc.service.IBlackListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Wilson
 * @since 2022-09-29
 */
@Service
public class BlackListServiceImpl extends ServiceImpl<BlackListMapper, BlackList> implements IBlackListService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public JSONResult saveblack(BlackList blackList) {
        String phone = blackList.getPhone();
        BlackList oneBlack = selectByPhone(phone);
        if (oneBlack == null){
            // 不存在
            blackList.setTime(new Date());
            insert(blackList);
            String key  = String.format(CommonConstants.Register_BLACK_PREFIX,phone);
            redisTemplate.opsForValue().set(key,blackList);
        } else {
            // 存在
            Wrapper<BlackList> wrapper = new EntityWrapper<>();
            wrapper.eq("phone",oneBlack.getPhone());
            update(blackList,wrapper);
        }
        return JSONResult.success("添加成功");
    }

    private BlackList selectByPhone(String phone) {
        Wrapper<BlackList> wrapper = new EntityWrapper<>();
        wrapper.eq("phone",phone);
        return selectOne(wrapper);
    }
}
